package com.heima.app.gateway.filter;


import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.JwtUtils;
import com.heima.utils.common.Payload;
import com.heima.utils.common.RsaUtils;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.swing.*;
import java.security.PublicKey;
/**
 * 统一鉴权过滤器
 */
@Component
public class AuthroizationFilter implements GlobalFilter {
    //公钥文件路径
    @Value("${leadnews.jwt.publicKeyPath}")
    private String publicKeyPath;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //判断是否为登录请求，为登录请求直接放行
        //获取uri路径
        String uri = request.getURI().getPath();
        if (uri.contains("/login")) {
            //放行请求
            return chain.filter(exchange);
        }


        //取出token请求，如果不包含token请求头直接拒绝
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            //直接拒绝
            //返回401状态码,spring自带的枚举项
            response.setStatusCode(HttpStatus.UNAUTHORIZED);

            //结束请求
            return response.setComplete();
        }


        //验证token合法性，如果不合法，则拒绝放行。如果合法，放行请求
        /**
         * 参数一：需要验证的token字符串
         * 参数二：公钥数据
         * 参数三：登录对象类型
         */
        //读取公钥数据
        try {
            PublicKey publicKey = RsaUtils.getPublicKey(publicKeyPath);
            //getInfoFromToken() 既可以验证合法性，也可以获取用户信息
            Payload<ApUser> fromToken = JwtUtils.getInfoFromToken(token, publicKey, ApUser.class);
            //从token取出用户信息
            ApUser user = fromToken.getInfo();
            //将用户数据写入请求头，随着请求头传递到后续的微服务中使用
            request.mutate().header("userId", user.getId().toString());
            //放行请求
            return chain.filter(exchange);

        } catch (Exception e) {
            //直接拒绝
            //返回401状态码,spring自带的枚举项
            response.setStatusCode(HttpStatus.UNAUTHORIZED);

            //结束请求
            return response.setComplete();
        }

    }
}
